

import 'dart:ui';

import 'package:alip_app/AppStates/NetworkApi.dart';
import 'package:alip_app/Entities/CategoryResult.dart';
import 'package:alip_app/StateManagement/ModelProvider.dart';
import 'package:alip_app/UI/Pages/TopicsPage.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

class CategoriesPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _State();
  }
}

class _State extends State<CategoriesPage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    final webApi = ModelContainer.of<NetworkApi>(context).model.api;

    Widget buildingWidget = FutureBuilder<CategoryResult>(
      future: webApi.getCategories(),
      builder: (context, snapshot) {
        if (snapshot.hasError) return Center(child: Text("An error occurred while loading category data, here is the error message:\n${snapshot.error}"),);
        if (snapshot.hasData) return ListView(
          padding: EdgeInsets.all(10.0),
          children: [
            SizedBox(height: 80.0,),
            ...snapshot.data.list.map((e) => _buildCategoryItem(context, e)).toList(),
            SizedBox(height: 80.0,),
          ],
        );
        return Center(
          child: CircularProgressIndicator(),
        );
      },
    );
    return buildingWidget;
  }

  Widget _buildCategoryItem(BuildContext context, Category category) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).backgroundColor,
        borderRadius: BorderRadius.circular(15.0),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(category.boardCategoryName, style: Theme.of(context).textTheme.headline6,),
          GridView(
            gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(childAspectRatio: 1, maxCrossAxisExtent: 120.0),
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            children: category.boardList.map((subCategory) => _buildSubCategory(context, subCategory)).toList(),
          ),
        ],
      ),
      margin: EdgeInsets.all(10.0),
      padding: EdgeInsets.all(10.0),
    );
  }
  Widget _buildSubCategory(BuildContext context, SubCategory category) {
    Widget buildingWidget = Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Hero(
          tag: category.boardId,
          child: CircleAvatar(
            radius: 30.0,
            backgroundColor: Theme.of(context).scaffoldBackgroundColor,
            backgroundImage: CachedNetworkImageProvider(category.boardImg),
          ),
        ),
        Text(category.boardName, style: Theme.of(context).textTheme.subtitle2, textAlign: TextAlign.center,),
      ],
    );
    buildingWidget = InkWell(
      child: buildingWidget,
      onTap: () {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => _buildNewPage(context, category),));
      },
    );
    return buildingWidget;
  }
  
  Widget _buildNewPage(BuildContext context, SubCategory category) {
    final paddingTop = MediaQuery.of(context).padding.top;
    final height = paddingTop + 80;
    Widget buildingWidget = Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned.fill(child: TopicsPage(boardId: category.boardId, paddingHeight: height,),),
          Positioned(
            height: height,
            left: 0.0,
            top: 0.0,
            right: 0.0,
            child: ClipRRect(
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaY: 20.0),
                child: Container(
                  alignment: Alignment.bottomCenter,
                  color: Theme.of(context).backgroundColor,
                  child: ListTile(
                    leading: Hero(
                      tag: category.boardId,
                      child: CircleAvatar(
                        radius: 28.0,
                        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
                        backgroundImage: CachedNetworkImageProvider(category.boardImg),
                      ),
                    ),
                    title: Text(category.boardName),
                    subtitle: Text("جەمئىي ${category.topicTotalNum} دانە يازما، ${category.postsTotalNum} دانە يولانما"),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );

    buildingWidget = Directionality(child: buildingWidget, textDirection: TextDirection.rtl,);
    return buildingWidget;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
